package com.fc.common.security.service;

import com.fc.admin.api.dto.UserInfo;
import com.fc.admin.api.feign.RemoteUserService;
import com.fc.common.core.constant.CacheConstants;
import com.fc.common.core.constant.SecurityConstants;
import com.fc.common.core.utils.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @Description: 用户详细信息
 * @ClassName: FcAppUserDetailsServiceImpl
 * @Author: weisn
 * @Date: 2022/12/21 10:25
 * @Version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
public class FcAppUserDetailsServiceImpl implements FcUserDetailsService {
    private final RemoteUserService remoteUserService;

    private final CacheManager cacheManager;

    /**
     * 手机号登录
     * @param phone 手机号
     * @return
     */
    @Override
    @SneakyThrows
    public UserDetails loadUserByUsername(String phone) {
        Cache cache = cacheManager.getCache(CacheConstants.USER_DETAILS);
        if (cache != null && cache.get(phone) != null) {
            return (FcUser) cache.get(phone).get();
        }

        R<UserInfo> result = remoteUserService.infoByMobile(phone);

        UserDetails userDetails = getUserDetails(result);
        if (cache != null) {
            cache.put(phone, userDetails);
        }
        return userDetails;
    }

    /**
     * check-token 使用
     * @param fcUser user
     * @return
     */
    @Override
    public UserDetails loadUserByUser(FcUser fcUser) {
        return this.loadUserByUsername(fcUser.getPhone());
    }

    /**
     * 是否支持此客户端校验
     * @param clientId 目标客户端
     * @return true/false
     */
    @Override
    public boolean support(String clientId, String grantType) {
        return SecurityConstants.APP.equals(grantType);
    }
}
